package com.company.ems.controller;

import com.company.ems.dao.UserDAO;
import com.company.ems.dao.UserDAOImpl;
import com.company.ems.model.User;
import org.mindrot.jbcrypt.BCrypt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {


        // 如果已登录，重定向到 dashboard
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("user") != null) {
            response.sendRedirect("dashboard");
//            response.sendRedirect("/employee/list.jsp");
            return;
        }
        request.getRequestDispatcher("login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = userDAO.findByUsername(username);

        //明文密码
        if (user != null && password.equals(user.getPassword())) {
            // 登录成功，创建会话
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            session.setMaxInactiveInterval(30 * 60); // 30分钟超时

            // 重定向到主页
            response.sendRedirect("dashboard");
            //直接定向到

//            response.sendRedirect("list.jsp");
        } else {
            // 登录失败
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

        //使用BCrypt加密
//        if (user != null && BCrypt.checkpw(password, user.getPassword())) {
//            // 登录成功，创建会话
//            HttpSession session = request.getSession();
//            session.setAttribute("user", user);
//            session.setMaxInactiveInterval(30 * 60); // 30分钟超时
//
//            // 重定向到主页
//            response.sendRedirect("dashboard");
//            //直接定向到
//
////            response.sendRedirect("list.jsp");
//        } else {
//            // 登录失败
//            request.setAttribute("error", "用户名或密码错误");
//            request.getRequestDispatcher("login.jsp").forward(request, response);
//        }
    }
}